package com.tuocent.dagv2.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.tuocent.dagv2.common.AjaxResult;
import com.tuocent.dagv2.common.entity.ValidateCode;
import com.tuocent.dagv2.common.utils.TCUtil;
import com.tuocent.dagv2.common.utils.ValidateCodeUtil;
import com.tuocent.dagv2.common.utils.redis.RedisCache;
import com.tuocent.dagv2.constant.Constants;
import com.tuocent.dagv2.service.IValidateCodeService;
import jakarta.annotation.Resource;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class ValidateCodeServiceImpl implements IValidateCodeService {
    @Resource
    private RedisCache redis;

    @Override
    public ValidateCode get() {
        ValidateCodeUtil.Validate randomCode = ValidateCodeUtil.getRandomCode();//直接调用静态方法，返回验证码对象
        if (ObjectUtil.isNull(randomCode)) {
            return null;
        }

        String value = randomCode.getValue().toLowerCase();
        String md5Key = DigestUtils.md5Hex(value);
        String redisKey = getRedisKey(md5Key);
        redis.set(redisKey, value, 5L * 1000);   //5分钟过期
        String base64Str = randomCode.getBase64Str();
        return new ValidateCode(md5Key, TCUtil.getBase64Image(base64Str));
    }

    /**
     * 获取redis key
     *
     * @param md5Key value的md5加密值
     */
    public String getRedisKey(String md5Key) {
        return Constants.VALIDATE_REDIS_KEY_PREFIX + md5Key;
    }


    @Override
    public Boolean check(String key, String code) {
        System.err.println(getRedisKey(key));
        if (!redis.exists(getRedisKey(key))) {
            return false;
        }
        Object redisValue = redis.get(getRedisKey(key));
        if (ObjectUtil.isNull(redisValue)) {
            return false;
        }
        return redisValue.equals(code.toLowerCase());
    }

    public AjaxResult getVerificationCode(Map<String, String> values) throws Exception {
        String phone = values.containsKey("phone") ? values.get("phone") : "";
        if ("".equals(phone)) {
            return AjaxResult.error("请输入注册手机号码");
        }
        String vCode = ValidateCodeUtil.getRandomCode().getValue();
        String redisKey = getRedisKey(phone);
        redis.set(redisKey, vCode, 5L * 1000);   //5分钟过期
        //if (SendSmsUtil.sendSms(phone, vCode)) {
        //    return CommonResult.success("验证信息发送成功");
        //} else {
        //    return CommonResult.failed("发送信息失败");
        //}
        return AjaxResult.success();

    }
}
